import axios from 'axios'
// import { Notification } from 'element-ui'
import store from '@/store'
import {machineIdSync} from 'node-machine-id';
import {getStore} from "./storage";

// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    withCredentials: true
});


// request interceptor
service.interceptors.request.use(
    config => {
        // console.log(config)
        // config.baseURL = httpEnvironment[config.link]
        // do something before request is sent
        console.log('-------------------------------');
        console.group('发送http请求');
        console.log(`baseURL: ${config.baseURL}`);
        console.log(`url: ${config.url}`);
        console.groupEnd();
       console.log( getStore('token'))
        config.headers['X-Token'] = getStore('token') || '';
        config.headers['uuid'] = machineIdSync();
        return config
    },
    error => {
        // do something with request error
        console.log(error); // for debug
        return Promise.reject(error)
    }
);

// response interceptor
service.interceptors.response.use(
    response => {
        console.group(`http请求成功回调`)
        console.log('请求返回值：', response.data)
        console.groupEnd()
        console.log('-------------------------------')

        if (response.data.code === 401) {
            // Notification({
            //   title: '错误',
            //   message: response.data.message,
            //   type: 'error',
            //   duration: 5 * 1000
            // })
            // store.dispatch('user/resetToken').then(() => {
            //     location.reload()
            // })
        }
        if (response.data.code === 500) {
            // Notification({
            //   title: '错误',
            //   message: error.response.message,
            //   type: 'error',
            //   duration: 5 * 1000
            // })
            return Promise.reject(response.data || 'Error')
        }

        return response.data
    },
    error => {
        // for debug
        console.group('http请求失败回调')
        console.log(error.response)
        console.groupEnd()
        console.log('-------------------------------')

        return Promise.reject(error)
    }
)

export default service
